package com.itboye.sunsun.luntan;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout.LayoutParams;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.homesensen.alert.ByAlert;
import com.itboye.luntan.web.FlowLayout;
import com.itboye.sunsun.adapter.LunTanSouSuoSearAdapter;
import com.itboye.sunsun.adapter.LunTanSouSuoSearTieziAdapter;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.LuntanTieziSouBeans;
import com.itboye.sunsun.beans.LunTanHomePageBean.LunTanItemBean;
import com.itboye.sunsun.beans.LuntanTieziSouBeans.LunTanTieziSearBean;
import com.itboye.sunsun.beans.WeChatBean;
import com.itboye.sunsun.beans.WeChatBean.WeChaReMenBean;
import com.itboye.sunsun.custome.LunTanEdittext;
import com.itboye.sunsun.custome.XListView;
import com.itboye.sunsun.custome.XListView.IXListViewListener;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.itboye.sunsunhome.R;
import com.umeng.socialize.utils.Log;

/**
 * 搜索
 * 
 * @author 余 焱
 * 
 */
public class LuntanSearchActivity extends BaseActivity implements
		OnClickListener, IXListViewListener {

	XListView listView;

	private LunTanEdittext et_search;
	private BaseAdapter adapter;

	private TextView delete;
	PopupWindow popupWindow;
	private RelativeLayout realyouttitl;
	private TextView spinner, tvLutanSize;
	private int num = 1;// 1表示通过帖子名称搜索 2表示通过发帖人昵称进行搜索

	List<WeChaReMenBean> channelList = new ArrayList<WeChaReMenBean>();
	List<LunTanTieziSearBean> list = new ArrayList<LunTanTieziSearBean>();

	private RelativeLayout re_nodate;
	private ImageView spanner_icon;
	GridView otherGridView;
	FlowLayout tagGroup;
	RelativeLayout realyoutTop;
	TextView[] childView;
	List<WeChaReMenBean> wordQueryModels = new ArrayList<WeChaReMenBean>();
	private LinearLayout linLuntan;

	private int page_num = 1;// 页码数
	
	private int isnum;
String title;
	private ImageView back;
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.itboye.sunsun.support.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	@SuppressLint("InlinedApi")
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.activity_luntan_search);
		setStatusBarColor(R.color.home_blue);
		re_nodate = (RelativeLayout) findViewById(R.id.re_nodate);
		re_nodate.setVisibility(View.GONE);
		listView.setXListViewListener(this);
		listView.setPullLoadEnable(true);
		listView.setPullRefreshEnable(true);
		et_search.addTextChangedListener(textWatcher);
		linLuntan.setVisibility(View.GONE);
		// otherGridView=(GridView)findViewById(R.id.otherGridView);
		//
		// menAdapter=new LunTanReMenAdapter(LuntanSearchActivity.this,
		// channelList);
		// otherGridView.setAdapter(menAdapter);
		PublicReMen();
		popupWindow = new PopupWindow();
		

		// listview点击事件
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
//				position--;

				Intent intent = new Intent(LuntanSearchActivity.this,
						TieZiDetailActivity.class);
				LunTanTieziSearBean bean = list.get(position-1);
				intent.putExtra("fid", bean.getFid());
				intent.putExtra("tid", bean.getTid());

				startActivity(intent);
			}
		});

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		
		case R.id.back:
			finish();
			break;
		
		case R.id.realyouttitl:
			PuPoWindow(v);
			break;

		case R.id.re_shuizu_search:// 帖子
			
			spinner.setText("按标题");
			num = 1;
			popupWindow.dismiss();
			
			break;
		case R.id.re_shuizu_message:// 用户
		

			spinner.setText("按作者");
			num = 2;
			popupWindow.dismiss();
			
			break;
		case R.id.delete:// 搜索
			realyoutTop.setVisibility(View.VISIBLE);

			if (num == 1) {
				list.clear();
				pullUp();
				adapter = new LunTanSouSuoSearTieziAdapter(list,
						LuntanSearchActivity.this);
				listView.setAdapter(adapter);
				tvLutanSize.setText("共搜索到" + adapter.getItem(list.size())
						+ "条数据");
				// adapter.notifyDataSetChanged();
			} else {
				list.clear();
				pullUp();
				adapter = new LunTanSouSuoSearAdapter(list,
						LuntanSearchActivity.this);
				listView.setAdapter(adapter);
				tvLutanSize.setText("共搜索到" + adapter.getItem(list.size())
						+ "条数据");
				// adapter.notifyDataSetChanged();
			}
			break;
		default:
			break;
		}
	}

	
	TextWatcher textWatcher=new TextWatcher() {
		
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub
			System.out.println("<><><><<<<<<<<>>>>>>>>>>>>>>>>>>onTextChanged"+et_search.getText().toString());
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			System.out.println("<><><><<<<<<<<>>>>>>>>>>>>>>>>>>beforeTextChanged"+et_search.getText().toString());
		}
		
		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			System.out.println("<><><><<<<<<<<>>>>>>>>>>>>>>>>>>afterTextChanged"+et_search.getText().toString());
		}
	};
	/**
	 * 论坛搜索类型切换
	 * 
	 * @param v
	 */
	public void PuPoWindow(View v) {

		View view = LayoutInflater.from(this).inflate(
				R.layout.item_luntan_sousuo, null);
		RelativeLayout re_shuizu_search = (RelativeLayout) view
				.findViewById(R.id.re_shuizu_search);
		RelativeLayout re_shuizu_message = (RelativeLayout) view
				.findViewById(R.id.re_shuizu_message);

		re_shuizu_search.setOnClickListener(this);
		re_shuizu_message.setOnClickListener(this);
		popupWindow = new PopupWindow(view, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.showAsDropDown(v);
	}

	/**
	 * 搜索帖子
	 */
	private void pullUp() {
		// 设置num默认为1
		showProgressDialog("搜索中，请稍后", true);
		MyJsonRequest.Builder<LuntanTieziSouBeans> builder = new MyJsonRequest.Builder<LuntanTieziSouBeans>()
				.apiVer("100").typeKey("BY_BbsFavorite_searchcard")
				.param("ttype", num + "")
				.param("name", et_search.getText().toString())
				.param("page_no", page_num).param("page_size", 8)
				.requestListener(new XRequestListener<LuntanTieziSouBeans>() {

					@Override
					public void onResponse(final LuntanTieziSouBeans bean) {
						// list.clear();
						if (page_num == 1) {

							list.clear();
						}
						if (et_search.getText().toString().isEmpty()) {
							ByAlert.alert("输入不能为空");
							closeProgressDialog();
							return;
						}
						if (bean.getCount() > 0 && bean.getList() != null) {
							

							tvLutanSize.setText("共搜索到" + bean.getCount()
									+ "条数据");
							re_nodate.setVisibility(View.GONE);
							linLuntan.setVisibility(View.VISIBLE);
							list.addAll(bean.getList());
							adapter.notifyDataSetChanged();

						} else if (list == null) {
							linLuntan.setVisibility(View.GONE);
							re_nodate.setVisibility(View.VISIBLE);
							ByAlert.alert("没有找到理想的数据....");
						} else if (list.size() <= 0) {
							linLuntan.setVisibility(View.GONE);
							re_nodate.setVisibility(View.VISIBLE);
							ByAlert.alert("没有找到理想的数据....");
						}
						try {
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						// onPullDownError(adapter, xlistview, exception,
						// code,p[]\l;
						listView.stopLoadMore();
						System.out.println("" + msg);
						// msg);
						try {
							closeProgressDialog();

						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				});

		MyJsonRequest<LuntanTieziSouBeans> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	private void PublicReMen() {
		// 设置num默认为1
		MyJsonRequest.Builder<WeChatBean> builder = new MyJsonRequest.Builder<WeChatBean>()
				.typeKey("BY_BbsUserCenter_hotRecommend").apiVer("100")
				.requestListener(new XRequestListener<WeChatBean>() {

					@Override
					public void onResponse(final WeChatBean bean) {
						wordQueryModels.clear();
						if (bean.getCount() > 0) {
							wordQueryModels.addAll(bean.getList());
							onTextVIew();

						}

					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						// onPullDownError(adapter, xlistview, exception,
						// code,p[]\l;
						listView.stopLoadMore();
						System.out.println("" + msg);
						// msg);
					}
				});

		MyJsonRequest<WeChatBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	public void onTextVIew() {
		childView = new TextView[wordQueryModels.size()];
		for (int i = 0; i < wordQueryModels.size(); i++) {
			tagGroup = (FlowLayout) findViewById(R.id.tagGroup);
			View view = LayoutInflater.from(LuntanSearchActivity.this).inflate(
					R.layout.textview, null);
			TextView textView = (TextView) view.findViewById(R.id.text);
			ImageView img_del = (ImageView) view.findViewById(R.id.img_del);
			img_del.setVisibility(View.GONE);
			tagGroup = (FlowLayout) findViewById(R.id.tagGroup);
			textView.setText(wordQueryModels.get(i).getName() + "");
			textView.setGravity(Gravity.CENTER);
			textView.setTextColor(getResources().getColor(R.color.black));
			// textView.setBackgroundDrawable(getResources()));
			textView.setTag(i);
			childView[i] = textView;
			childView[i].setTag(i);
			android.widget.RelativeLayout.LayoutParams lP = new android.widget.RelativeLayout.LayoutParams(
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
			lP.setMargins(10, 10, 10, 10);
			tagGroup.addView(view, lP);

			childView[i].setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					et_search.setText(childView[Integer.parseInt(v.getTag()
							+ "")].getText().toString());

				}
			});

		}
	}

	@Override
	public void onRefresh() {
		page_num = 1;
		pullUp();
		stopload();
	}

	@Override
	public void onLoadMore() {
		page_num++;
		pullUp();
		stopload();

	}

	public void stopload() {
		listView.stopLoadMore();
		listView.stopRefresh();
	}

}
